package cn.q3c.parse.commons.wordpress;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public class WordPressAPI {

	/**
	 * 发布文章
	 * 
	 * @throws MalformedURLException
	 * @throws XmlRpcException
	 */
	public static String newPost(String xmlrpcurl, String username,
			String password, Post post) throws MalformedURLException,
			XmlRpcException {

		XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
		config.setServerURL(new URL(xmlrpcurl));
		XmlRpcClient client = new XmlRpcClient();
		client.setConfig(config);

		Map<String, Object> postMap = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(post.getPost_type())) {
			postMap.put("post_type", post.getPost_type());
		}

		if (StringUtils.isNotBlank(post.getPost_status())) {
			postMap.put("post_status", post.getPost_status());
		}

		if (StringUtils.isNotBlank(post.getPost_title())) {
			postMap.put("post_title", post.getPost_title());
		}

		if (StringUtils.isNotBlank(post.getPost_excerpt())) {
			postMap.put("post_excerpt", post.getPost_excerpt());
		}

		if (StringUtils.isNotBlank(post.getPost_content())) {
			postMap.put("post_content", post.getPost_content());
		}

		if (ArrayUtils.isNotEmpty(post.getCustom_fields())) {
			postMap.put("custom_fields", post.getCustom_fields());
		}

		if (post.getTerms_names() != null && !post.getTerms_names().isEmpty()) {
			postMap.put("terms_names", post.getTerms_names());
		}

		Object[] params = new Object[] { "1", username, password, postMap, true }; // 1代表正式发布，0代表草稿
		String ob = (String) client.execute("wp.newPost", params);

		return ob;
	}

}
